package com.ihd.ihardware.view.tzc.main.view;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ihd.ihardware.R;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.common.adapter.TabIndicatorFragmentAdapter;
import com.ihd.ihardware.common.utils.DataUtils;
import com.ihd.ihardware.databinding.BalanceActivityBinding;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.pojo.UpdateRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.service.StepService;
import com.ihd.ihardware.view.tzc.discovery.view.DiscoveryFragment;
import com.ihd.ihardware.view.tzc.health.view.HealthFragment;
import com.ihd.ihardware.view.tzc.main.viewmodel.BalanceViewModel;
import com.ihd.ihardware.view.tzc.me.view.MeFragment;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import java.util.ArrayList;
import java.util.List;

import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.base.BaseFragment;
import cn.wowjoy.commonlibrary.rxbus.RxBus;
import cn.wowjoy.commonlibrary.utils.AppActivityManager;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.HexUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.SysUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;

public class BalanceActivity extends BaseActivity<BalanceActivityBinding, BalanceViewModel> {
    private List<Integer> icons;
    private List<String> titles;
    private List<BaseFragment> fragments;
    private IndicatorViewPager indicatorViewPager;
    private TabIndicatorFragmentAdapter tabIndicatorFragmentAdapter;
    private long exitTime = 0L;
    private BluetoothStateListener mBluetoothStateListener;
    private MDialog dg;

    private void initData() {
        titles = new ArrayList<>();
        titles.add("健康");
        titles.add("发现");
//        titles.add("服务商");
        titles.add("我的");

        icons = new ArrayList<>();
        icons.add(R.drawable.home_tab_workbench_selector);
        icons.add(R.drawable.home_tab_patient_selector);
//        icons.add(R.drawable.home_tab_news_selector);
        icons.add(R.drawable.home_tab_personal_selector);

        fragments = new ArrayList<>();
        fragments.add(HealthFragment.newInstance("", ""));
        fragments.add(DiscoveryFragment.newInstance("", ""));
//        fragments.add(SellerFragment.newInstance("", ""));
        fragments.add(MeFragment.newInstance("", ""));

        if (android.os.Build.VERSION.SDK_INT >= 26)
            startForegroundService(new Intent(this, StepService.class));
        else
            startService(new Intent(this, StepService.class));

        if (android.os.Build.VERSION.SDK_INT >= 23) {
            try {
                PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
                boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(getPackageName());
                if (!hasIgnored) {
                    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        initData();
        binding.tabIndicator.setOnTransitionListener(new OnTransitionTextListener().setColor(ContextCompat.getColor(this, R.color.C_317DCD), ContextCompat.getColor(this, R.color.C_B5B7BF)));
        indicatorViewPager = new IndicatorViewPager(binding.tabIndicator, binding.vp);
        tabIndicatorFragmentAdapter = new TabIndicatorFragmentAdapter(getSupportFragmentManager());
        tabIndicatorFragmentAdapter.setData(icons, titles, fragments);
        indicatorViewPager.setAdapter(tabIndicatorFragmentAdapter);
        binding.vp.setOffscreenPageLimit(3);

        mBluetoothStateListener = new BluetoothStateListener() {
            @Override
            public void onBluetoothStateChanged(boolean openOrClosed) {
                if (openOrClosed)
                    searchNow();
            }
        };
        BLEUtils.getInstance().registerBluetoothStateListener(mBluetoothStateListener);

        UserInfoRes.DataBean ud = new Gson().fromJson(SPUtils.getString(AppConstans.USER_INFO, ""), UserInfoRes.DataBean.class);

        setRx(AppConstans.UPGRADE, new BaseConsumer<UpdateRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(UpdateRes updateInfo) {
                if (updateInfo.getData().getVersionNumber() > SysUtils.getVersionCode()) {
                    dg = DialogUtils.alertDialog(BalanceActivity.this, MDialog.DG_TYPE.ALERT, updateInfo.getData().getDescription(), "以后再说", "立即更新",
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dg.cancel();
                                    if (updateInfo.getData().getForceUpdate() == 1)
                                        AppActivityManager.getInstance().AppExit(BalanceActivity.this);
                                }
                            }, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dg.cancel();
                                    ToastUtils.showLong(BalanceActivity.this, "正在下载...");
                                    viewModel.download(updateInfo);
                                }
                            });
                }
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(BalanceActivity.this, error.getMessage());
            }
        });

        LiveEventBus.get().with(AppConstans.DOWNLOAD_APK, UpdateRes.class).observe(this, new Observer<UpdateRes>() {
            @Override
            public void onChanged(@Nullable UpdateRes s) {
                SysUtils.installApk(BalanceActivity.this, AppConstans.UPDATE_PATH);
            }
        });

        viewModel.checkUpdate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        searchNow();
    }

    private void searchNow() {
        BluetoothUtils.getBluetoothAdapter().setName("VCHM");
        BLEUtils.getInstance().search(new SearchRequest.Builder().searchBluetoothLeDevice(86400000).build(), new SearchResponse() {
            @Override
            public void onSearchStarted() {
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                Beacon beacon = new Beacon(device.scanRecord);
                byte[] mByte = new byte[31];
                System.arraycopy(beacon.mBytes, 0, mByte, 0, beacon.mBytes.length);
                if (DataUtils.isValidDevice(mByte)) {
                    String temp = SPUtils.getString(AppConstans.DEVICES, "");
                    if (!TextUtils.isEmpty(temp)) {
                        boolean hasCheng = false;
                        String localMac = "";
                        String remoteMac = device.getAddress().replace(":", "").toUpperCase();
                        List<DeviceListRes.DataBean.ListBean> ddls = new Gson().fromJson(temp, new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                        }.getType());
                        for (DeviceListRes.DataBean.ListBean ddl : ddls) {
                            if ("0".equals(ddl.getType()) || "1".equals(ddl.getType())) {
                                hasCheng = true;
                                localMac = ddl.getMac().replace(":", "").toUpperCase();
                            }
                        }
                        if (!hasCheng)
                            RxBus.getInstance().post(AppConstans.BINDING, beacon);
                        else {
                            if (remoteMac.equals(localMac))
                                RxBus.getInstance().post(AppConstans.CHENG, beacon);
                        }
                    } else {
                        RxBus.getInstance().post(AppConstans.BINDING, beacon);
                    }
                }
            }

            @Override
            public void onSearchStopped() {
            }

            @Override
            public void onSearchCanceled() {
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.balance_activity;
    }

    @Override
    protected Class<BalanceViewModel> getViewModelClass() {
        return BalanceViewModel.class;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BLEUtils.getInstance().unregisterBluetoothStateListener(mBluetoothStateListener);
        BLEUtils.getInstance().stopSearch();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
